import 'package:hi_net/request/hi_base_request.dart';

import 'core/dio_adapter.dart';
import 'core/hi_error.dart';
import 'core/hi_net_adapter.dart';

class HiNet {
  HiNet._();
  static HiNet? _instance;
  static HiNet getInstance() {
    if (_instance == null) {
      _instance = HiNet._();
    }
    return _instance!;
  }

  Future fire(HiBaseRequest request) async {
    HiNetResponse? response;
    var error;

    try {
      response = await send(request);
    } on HiNetError catch (e) {
      error = e;
      response = e.data;
      printLog(e.message);
    } catch (e) {
      error = e;
      printLog(e);
    }
    if (response == null) {
      print(error);
    }

    var result = response?.data;
    print(result);
    //解析状态码
    var status = response?.statusCode;
    switch (status) {
      case 200:
        return result;
      case 401:
        throw NeedLogin();
      case 403:
        throw NeedAuth(result.toString(), data: result);
      default:
        throw HiNetError(status!!, response.toString(), data: result);
    }

    return result;
  }

  Future<dynamic> send<T>(HiBaseRequest request) async {
    printLog('url:${request.url()}');
    /* printLog('method:${request.httpMethod()}');
    request.addHeader('token', '123456');
    printLog('header:${request.header}');
    return Future.value({
      'statusCode': 20,
      'data': {'code': 0, 'message': 'success!'}
    });*/
    //使用 Mock 发送数据请求
    //  HiNetAdapter adapter = MockAdapter();
    HiNetAdapter adapter = DioAdapter();
    return adapter.send(request);
  }

  void printLog(log) {
    print('hi_net:${log.toString()}');
  }
}
